package com.fingard.dsp.bank.directbank.sdebank01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.sql.Connection;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
/**
 * @author: liuxb
 * @create: 2019-12-06 15:04
 * @version: 1.0
 **/
public class SDEBANK01BatPayRec extends SDEBANK01Base implements IBatPayRec {
    /**
     * 批量代付提交
     *
     * @param p_req1988 批量代付请求对象
     * @return 批量代付响应对象
     * @throws Exception
     */
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req1988.reqHeader);
        retAts.writeStart();
        try {
            //======拼接报文======
            //拼接请求报文体
            SDEBANK01Header header = new SDEBANK01Header();
            header.TrsCode = "B2EUploadSalaryData2HostV2";//银行交易码
            header.ERPTrsTimestamp = p_req1988.reqHeader.transTime;//指令请求时间
            header.ERPJnlNo = p_req1988.reqHeader.transSeqID;//生成交易流水号
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入SDEBANK01通用的头部节点
            writeCommonHeader(xmlWriter, header);
            xmlWriter.writeStartElement("Body");
//            xmlWriter.writeElementString("OptType", p_req1988.readedDetail.lioperType);//业务类型 1－代付 2－代收
            xmlWriter.writeElementString("OptType", "1");//业务类型 1－代付 2－代收

            xmlWriter.writeElementString("Currency", convertCurToBank(p_req1988.ownCur));//币种
            xmlWriter.writeElementString("PayerCurrency", convertCurToBank(p_req1988.ownCur));//付款币种
            xmlWriter.writeElementString("PayerAmount", p_req1988.totalAmt);//支付金额
            xmlWriter.writeElementString("PayerAcNo", p_req1988.ownAct);//付款账号
            xmlWriter.writeElementString("PayerAcName", p_req1988.ownActName);//付款账户户名
            xmlWriter.writeElementString("TrsPassword", "888888");//账户支取密码
            xmlWriter.writeElementString("TotalCount", p_req1988.totalNum);//总笔数
            xmlWriter.writeElementString("Remark", p_req1988.payType);//用途（交易类型）

            String transCode1 = "";
            String s = "";
            xmlWriter.writeStartElement("List");
            while (p_req1988.readRecord()) {
                transCode1 = p_req1988.readedDetail.purpose;//业务代码
                s = p_req1988.readedDetail.sameBnk;
                xmlWriter.writeStartElement("Map");
                xmlWriter.writeElementString("PayeeAmount", p_req1988.readedDetail.payAmount);//金额
                xmlWriter.writeElementString("PayeeAcNo", p_req1988.readedDetail.recAct);//对方账号
                xmlWriter.writeElementString("PayeeAcName", p_req1988.readedDetail.recName);//对方账户户名
//                xmlWriter.writeElementString("Remark", p_req1988.readedDetail.purpose);//用途（交易类型）
                xmlWriter.writeEndElement();
            }
            xmlWriter.writeEndElement();
            String cc = sub(transCode1);
            if (!"".equals(cc)){
                xmlWriter.writeElementString("OptCode", cc);//业务代码
            }else {
                xmlWriter.writeElementString("OptCode", convertOptCodeToBank(transCode1));//业务代码
            }
            if (s != null && s.equals("1")) {//同行
                xmlWriter.writeElementString("DataType", "1");//数据类型 1－本行 2－他行(暂时不支持他行)
            } else if (s != null && s.equals("0")) {//他行
                xmlWriter.writeElementString("DataType", "2");//数据类型 1－本行 2－他行(暂时不支持他行)
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "转账类型未知";
            }
            xmlWriter.writeEndDocument();

// 发送给银行获得应答报文
            String[] retStrArr = sendToBank(xmlWriter.toXmlString(), header);
            //模拟银行返回
//            String s = "<Message>\n" +
//                    "\t<Head>\n" +
//                    "\t\t<IBSReturnCode>000000</IBSReturnCode>\n" +
//                    "\t\t<IBSReturnMsg>成功！</IBSReturnMsg>\n" +
//                    "\t\t<IBSJnlNo>9126141</IBSJnlNo>\n" +
//                    "\t</Head>\n" +
//                    "\t<Body>\n" +
//                    "\t\t<HostBatchId>7</HostBatchId>\n" +
//                    "\t\t<BatchId>9126142</BatchId>\n" +
//                    "\t</Body>\n" +
//                    "</Message>\n";
//            String[] retStrArr = new String[]{"", s};

            if (retStrArr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(retStrArr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                    String tmpRetInfo = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                    header.ERPJnlNo = tmpBkReader.getFirstText("/Message/Head/IBSJnlNo");//交易流水号
                    if ("000000".equals(tmpRetCode)) {
                        retAts.respCode = "0";
                        retAts.reqSeqID = p_req1988.reqBatchNO;
                        retAts.respInfo = tmpRetCode + "+" + tmpRetInfo;
                        retAts.transState = "Paying";
                        retAts.payInfoCode = "Paying";

                        //记录ats支付流水号对应的银行指令流水号，供查询状态接口使用
                        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                        Connection conn = FGBiz.getLocalDbConn();//取本地文件数据库连接
                        //批号
                        JDBCHelper.update(conn, INSERTSEQTWO, new Object[]{uuid, p_req1988.reqHeader.bankCode, Format.Date8Format.format(new Date()), p_req1988.reqBatchNO, tmpBkReader.getFirstText("/Message/Body/HostBatchId"), tmpBkReader.getFirstText("/Message/Body/BatchId")});

                    } else {
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(tmpRetInfo);
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpSbMsg.toString());
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(retStrArr[1].toString());
            }

        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.toString();
            WriteBankLogLn("批量代发异常：" + e);
            e.printStackTrace();
        }
        retAts.writeRetToATS();
        return retAts;
    }

    /**
     * 批量代付状态查询
     *
     * @param p_req1998 批量代付查询请求对象
     * @return 批量代付响应对象
     * @throws Exception
     */
    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        retAts.writeStart();
        try {
            retAts.reqSeqID = p_req1998.reqBatchNO;
            SDEBANK01Header tmpBnkHeader = new SDEBANK01Header();
            tmpBnkHeader.TrsCode = "B2EDownloadSalaryResV2";
            tmpBnkHeader.ERPJnlNo = getQryTransID();//生成交易流水号
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter, tmpBnkHeader);
            xmlWriter.writeStartElement("Body");
//            XElement tmpElement =  new XElement("Body","");
            Connection conn = FGBiz.getLocalDbConn();
            Map<String, Object> selMap = JDBCHelper.execQuerySingle(conn, SELECTSEQTWO, new Object[]{p_req1998.reqHeader.reqSeqID, p_req1998.reqHeader.bankCode});
            if (selMap.size() > 0) {
                xmlWriter.writeElementString("HostBatchId", selMap.get("BANKREQSEQID").toString());//网银批号
                xmlWriter.writeElementString("BatchId", selMap.get("BANKREQBATCHNO").toString());//银行主机批号

                xmlWriter.writeElementString("DataType", "0");//数据类型

            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "交易流水号关联映射异常，请检查";
                retAts.writeBeforeDetail();
                retAts.writeAfterDetail();
                return retAts;
            }

            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();//写入报文完成

            // 发送给银行获得应答报文
            String[] resultBank = sendToBank(xmlWriter.toXmlString(), tmpBnkHeader);
            //模拟银行返回
//            String s = "<Message>\n" +
//                    "\t<Head>\n" +
//                    "\t\t\t<IBSReturnCode>000000</IBSReturnCode>\n" +
//                    "\t\t\t<IBSReturnMsg>银企交易成功！</IBSReturnMsg>\n" +
//                    "\t</Head>\n" +
//                    "<Body>\n" +
//                    "\t\t  <List>\n" +
//                    "\t\t\t\t<Map>\n" +
//                    "\t\t\t\t\t<EmployeeNo>001</EmployeeNo>\n" +
//                    "\t\t\t\t\t<PayeeDate>20120327</PayeeDate>\n" +
//                    "\t\t\t\t\t<PayeeAcNo>13618200017991</PayeeAcNo>\n" +
//                    "\t\t\t\t\t<PayeeAcName>测试客户1</PayeeAcName>\n" +
//                    "\t\t\t\t\t<PayeeAmount>300</PayeeAmount>\n" +
//                    "\t\t\t\t\t<DisposalRes>3</DisposalRes>\n" +
//                    "\t\t\t\t\t<FailedReason>帐号不存在</FailedReason>\n" +
//                    "\t\t\t\t</Map>\n" +
//                    "\t\t\t\t<Map>\n" +
//                    "\t\t\t\t\t<EmployeeNo>003</EmployeeNo>\n" +
//                    "\t\t\t\t\t<PayeeDate>20120327</PayeeDate>\n" +
//                    "\t\t\t\t\t<PayeeAcNo>04618800081038</PayeeAcNo>\n" +
//                    "\t\t\t\t\t<PayeeAcName>测试客户2</PayeeAcName>\n" +
//                    "\t\t\t\t\t<PayeeAmount>400</PayeeAmount>\n" +
//                    "\t\t\t\t\t<DisposalRes>2</DisposalRes>\n" +
//                    "\t\t\t\t\t<FailedReason>成功</FailedReason>\n" +
//                    "\t\t\t\t</Map>\n" +
//                    "\t\t</List>\n" +
//                    "\t</Body>\n" +
//                    "</Message>\n";
//            String[] resultBank = new String[]{"", s};

            if (resultBank[0].length() == 0) {// 成功响应
                StringBuilder tmpSbMsg = new StringBuilder();//存提示信息
                XmlTextReader tmpBkReader = loadBankRespXmlReader(resultBank[1], tmpSbMsg);// 把银行返回报文转成XmlTextReader格式
                if (tmpBkReader != null) {// 返回报文的内容不为空
                    String IBSReturnCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                    String IBSReturnMsg = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                    if ("000000".equals(IBSReturnCode)) {
                        retAts.respCode = "0";
                        retAts.reqSeqID = p_req1998.reqBatchNO;
                        retAts.respInfo = IBSReturnMsg;
                        retAts.writeBeforeDetail();
                        while (tmpBkReader.read("/Message/Body/List/Map")) {
                            String msg = tmpBkReader.readedXElement.getSingleTextNotNull("DisposalRes").trim();//处理代码
                            RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
//                            retAts.transState = IBSReturnCode + "+" + msg;//处理代码
//                            retAts.payInfoCode = IBSReturnCode + "+" + msg;//处理代码
                            tmpRetDetail.memo = tmpBkReader.readedXElement.getSingleTextNotNull("FailedReason").trim();//处理信息
                            tmpRetDetail.result = IBSReturnCode + "+" + msg;//处理代码
                            tmpRetDetail.payInfoCode = tmpRetDetail.result;//处理代码
                            tmpRetDetail.payAmount = tmpBkReader.readedXElement.getSingleTextNotNull("PayeeAmount").trim();//收款金额
                            tmpRetDetail.recName = tmpBkReader.readedXElement.getSingleTextNotNull("PayeeAcName").trim();//收款账户户名
                            tmpRetDetail.recAct = tmpBkReader.readedXElement.getSingleTextNotNull("PayeeAcNo").trim();//收款账号
                            tmpRetDetail.payAct = p_req1998.ownAct;//支付帐号
                            retAts.writeRetDetail(tmpRetDetail);
                        }
                    } else {
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(IBSReturnMsg);
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpSbMsg.toString());
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(resultBank[1].toString());
            }
            retAts.writeEnd();
            return retAts;


        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        }


        return null;
    }

    /**
     * 批量代扣提交
     *
     * @param p_req9188 批量代扣请求对象
     * @return 批量代扣响应对象
     * @throws Exception
     */
    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return null;
    }

    /**
     * 批量代收状态查询
     *
     * @param p_req9198 批量代扣查询请求对象
     * @return 批量代扣查询响应对象
     * @throws Exception
     */
    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return null;
    }
}
